<template>
<div class="com-container" @dblclick="reverMap">
	<div class="com-chart" ref="mapRef" id="mapRef"></div>
</div>
</template>
<script lang='ts' setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue';
import {getProvinceMapInfo} from '../utils/map_utils'
import * as echarts from 'echarts'
import '../../public/theme/chalk'
import {getmapdata} from '../api/api'
import socketService from '../api/socket_sever'
import { isValidKey } from '@/type/utils';
import { useStore } from 'vuex';
const store = useStore()
  const mapRef = ref()
	const state = reactive<{
    // myChart: echarts.ECharts | null,
    data: API.map[]
    currentPage: number
    totalPage: number
    setinter: number
    MapD: any
	}>({
    // myChart: null,
    data: [],// 服务器返回数据
    currentPage: 1,// 第几多少页
    totalPage: 0, // 一共多少页
    setinter: 0,
    MapD: {}
	})
  let myChart: echarts.ECharts | null = null
	onMounted(async() => {
      await initexs()
      screenAdapter()
      window.addEventListener('resize',screenAdapter )
	})
  onUnmounted(() => {
    clearInterval(state.setinter)
    socketService.Instance.unRegisterCallBack('map')
    window.removeEventListener('resize', screenAdapter)
  })
  // 初始化exs
  const initexs = async() => {
    var chartDom = document.getElementById('mapRef');
    const mapdata = await getmap()
    myChart = echarts.init(chartDom as HTMLElement, store.state.theme)
    echarts.registerMap('china', (mapdata) as any)
    const initoption = {
      title: {
        text: '▎商家分布',
        left: 20,
        top: 20
      },
      geo: {
        type: 'map',
        map: 'china',
        top: '5%',
        bottom: '5%',
        itemStyle: {
          areaColor: '#2e72bf',
          borderColor: '#333'
        }
      },
      legend: {
        left: '5%',
        bottom: '5%',
        orient: 'vertical'
      },
      grid: {
        top: '20%',
        left: '3%',
        right: '6%',
        bottom: '3%',
        containLabel: true
      }
    }
    myChart.on('click',(arg) => {
      const res:{key: string, path: string} = getProvinceMapInfo(arg.name)
      console.log(state.MapD[res.key]);
      if (!state.MapD[res.key]) {
        fetch(res.path)
          .then((res) => {return res.json(); })
          .then((data) => {
            state.MapD[res.key] = data
             echarts.registerMap(res.key, (data) as any)
             const initoption = {
              geo: {
                map: res.key,
              },
             }
            initoption && (myChart as  echarts.ECharts).setOption(initoption);
        })
          .catch((e) => {console.log(e.message);
        });
      } else {
         const initoption = {
          geo: {
            map: res.key,
          },
         }
        initoption && (myChart as  echarts.ECharts).setOption(initoption);
      }
    })
    initoption && (myChart as  echarts.ECharts).setOption(initoption);
    socketService.Instance.registerCallBack('map', getData)
    try {
      await getmapdata()
    } catch (error) {
      console.log(error);
    }
  }
    // 获取数据
  const getData = (data:API.map[]) => {
    state.data = data
    updataChar()
  }
    // 更新图表
  const updataChar = () => {
    const len = state.data.map( item => item.name )
    const showdata = state.data.map(item => {
      return {
        type: 'effectScatter',
        name: item.name,
        data: item.children,
        rippleEffect: {
          scale: 5,
          brushType: 'stroke'
        },
				coordinateSystem: 'geo'
      }
    })
    const dataoption = {
      legend: {
        data: len
      },
      series: showdata
    }
    dataoption && (myChart as  echarts.ECharts).setOption(dataoption);
  }
  const screenAdapter = () => {
    const titleFontSize = mapRef.value.offsetWidth / 100 * 3.6;
    // console.log(titleFontSize);
    const Adapteroption = {
      title: {
        textStyle: {
          fontSize: titleFontSize
        }
      },
			legend: {
				itemWidth: titleFontSize / 2,
				itemHeight: titleFontSize / 2,
        itemGap: titleFontSize / 3,
        textStyle: {
          fontSize: titleFontSize / 3
        }
			}
    }
    Adapteroption && (myChart as  echarts.ECharts).setOption(Adapteroption);
    (myChart as  echarts.ECharts).resize()
  }
  const getmap = async() => {
    let resdata
    await fetch('./map/china.json')
      .then((res) => {return res.json(); })
      .then((data) => {resdata = data})
      .catch((e) => {console.log(e.message);
    });
    return resdata
  }
 const reverMap = () => {
  const initoption = {
      geo: {
        map: 'china',
      },
  }
  initoption && (myChart as  echarts.ECharts).setOption(initoption);
 }
   defineExpose({
    screenAdapter
  })
  watch ( () => store.state.theme, async() => {
    // console.log('qweqwe');
    (myChart as echarts.ECharts).dispose();
    await initexs()
    screenAdapter()
    updataChar()
  }, {
    // immediate: true, // 是否初始化立即执行一次, 默认是false
    deep: true // 是否是深度监视, 默认是false
  })
</script>
<style lang='less' scoped>
</style>